package com.shop.entity;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class SecurityUserDetails implements UserDetails {
    private String username;
    private String password;
    private List<Role> roles;

    public SecurityUserDetails(LoginUser user, List<Role> roles) {
        this.username = user.getUserName();
        this.password = user.getPwd();
        this.roles = roles;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        System.out.println("-----getAuthorities----->");
        List<GrantedAuthority> authorities=new ArrayList<>();
        List<Role> roles=this.roles;
        System.out.println("---------用户名：-------------->"+username+"-pwd:"+password);
        for(Role role:roles){
            System.out.println("角色名称："+role.getRoleName());
            //注意：角色名称格式一定是"ROLE_roleName"
            authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
